﻿using System;
using System.Collections.Generic;
using System.Text;
using YouHP.Utility;
using YouHP.BLL;
using YouHP.Model;
using YouHP.Model.Group;

namespace YouHP.Pages.User.Group
{
    public class InvitePatientsAjax : BasePage
    {


        protected override void ShowPage()
        {
            base.ShowPage();

            int gid = RequestTools.GetQueryInt("gid", 0);
            int toUserId = RequestTools.GetQueryInt("toUserId", 0);

            //判断被邀用户与圈子关系
            GroupUserInfo info;
            info = GroupUserBLL.Instance.GetGroupUserInfo(gid, toUserId);
            if (info.Role == Constants.RoleAdmin || info.Role == Constants.RoleCreator || info.Role == Constants.RoleMember||info.Role == Constants.RoleBlacklist)
            {
                ResponseXML("1");
                return;
            }
            else if (info.Role == Constants.RoleInviting)
            {
                ResponseXML("2");
                return;
            }
            else
            {

                GroupInviteInfo NewInvite = new GroupInviteInfo();
                NewInvite.PostUserId = UserData.Id;
                NewInvite.PostUserName = UserData.UserName;
                NewInvite.ReceiveUserId = toUserId;
                NewInvite.GroupId = gid;
                NewInvite.GroupName = GroupBLL.Instance.GetGroupInfo(gid).GroupName;
                NewInvite.PostTime = DateTime.Now;

                bool succ = GroupBLL.Instance.AddGroupInvite(NewInvite);

                GroupUserInfo NewGroupUser = new GroupUserInfo();
                NewGroupUser.GroupId = gid;
                NewGroupUser.UserId = toUserId;
                NewGroupUser.UserName = UserBLL.Instance.GetUserInfo(toUserId).UserName;
                NewGroupUser.JoinTime = DateTime.Now;
                NewGroupUser.Role = Constants.RoleInviting;
                bool succ2;
                if (info.Role == Constants.RoleNoExsit)
                {
                    succ2 = GroupUserBLL.Instance.AddGroupUser(NewGroupUser);
                }
                else
                {
                    succ2 = GroupUserBLL.Instance.UpdateGroupUserRole(gid, toUserId, Constants.RoleInviting);
                }

                if (succ && succ2)
                {
                    ResponseXML("0");
                    return;
                }
                else
                {
                    ResponseXML("3");
                    return;
                }
            }

        }

        private void ResponseXML(string sb)
        {
            System.Web.HttpContext.Current.Response.Clear();
            System.Web.HttpContext.Current.Response.ContentType = "Text/html";
            System.Web.HttpContext.Current.Response.Expires = 0;

            System.Web.HttpContext.Current.Response.Write(sb);
            System.Web.HttpContext.Current.Response.End();
        }

    }
}
